<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="6">
        <!-- 新增角色按钮 -->
        <el-col :span="2">
          <el-button type="primary" @click="showAddRoleDialog">新增角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" stripe border>
        <el-table-column type="expand" width="50">
          <template slot-scope="scoped">
            <!-- for循环渲染一级权限,:class数组绑定要给数字添加引号  -->
            <el-row :class="['vcenter', 'rowBottomBorder', rowTopBorder]">
              <el-col :span="4">
                <el-tag type="danger" closable @close="deleteRole(scoped.row.id)">{{scoped.row.roleName}}</el-tag>
              </el-col>
              <el-col :span="20">
                <el-row v-for="(item2) in scoped.row.children" :key="item2.id" class="rowBottomBorder">
                  <el-col :span="4">
                    <el-tag type="warning" closable @close="deleteRoleRight(scoped.row.id,item2.id)">{{item2.authName}}</el-tag>
                  </el-col>
                  <el-col :span="20">
                    <el-tag type="info" closable v-for="(item3) in item2.children" :key="item3.id" @close="deleteRoleRight(scoped.row.id,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" width="50"></el-table-column>
        <!-- ID一般不在前端显示 -->
        <!-- <el-table-column label="角色ID" prop="id"></el-table-column> -->
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色说明" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" min-width="300px">
          <template slot-scope="scoped">
            <el-tooltip class="item" effect="dark" content="角色授权" placement="top">
              <el-button type="primary" icon="el-icon-setting" @click="showRoleAuthDialog(scoped.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="addRoleFormRef" :model="addRoleInfo" :rules="addRoleInfoRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色说明" prop="roleDesc">
          <el-input v-model="addRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配角色权限" :visible.sync="roleAuthDialogVisible" width="30%" :before-close="handleRoleAUthClose">
      <el-tree :data="rightsList"  node-key="id" :props="defaultProps" show-checkbox>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleAuthDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoleAuthInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        roleList: [],
        addRoleDialogVisible: false,
        roleAuthDialogVisible: false,
        addRoleInfo: {
          roleName: '',
          roleDesc: ''
        },
        addRoleInfoRules: {
          roleName: [{
            required: true,
            message: '角色名称不能为空',
            trigger: 'blur'
          }, {
            min: 3,
            max: 10,
            message: '角色名称长度必须大于3小于10',
            trigger: 'blur'
          }],
          roleDesc: [{
            required: true,
            message: '角色说明不能为空',
            trigger: 'blur'
          }, {
            min: 4,
            max: 10,
            message: '角色说明大于4个字符，小于10个字符',
            trigger: 'blur'
          }]
        },
        rightsList: [],
        roleAuth: {
          roleid: null,
          roleRights: ''
        },
        defaultProps: {
          label: 'authName',
          children: 'children'
        }
      }
    },
    created() {
      this.getRoleList()
    },
    methods: {
      async getRoleList() {
        const result = await this.$http.get('/roles')
        if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
        this.roleList = result.data
        // console.log(this.roleList)
        this.$message.success(result.meta.msg)
      },
      deleteRole(id) {
        console.log(id)
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          showCancelButton: true,
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const result = await this.$http.delete(`roles/${id}`)
          if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
          this.$message.success(result.meta.msg)
          this.getRoleList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      deleteRoleRight(roleid, rightsid) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          showCancelButton: true,
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const result = await this.$http.delete(`roles/${roleid}/rights/${rightsid}`)
          if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
          this.$message.success(result.meta.msg)
          this.getRoleList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      showAddRoleDialog() {
        this.addRoleDialogVisible = true
      },
      handleClose() {
        this.$refs.addRoleFormRef.resetFields()
      },
      submitAddRoleInfo() {
        // 提交前进行表单验证
        this.$refs.addRoleFormRef.validate(async valid => {
          if (!valid) return this.$message.error('表单验证失败，请检查后在提交')
          const result = await this.$http.post('roles', this.addRoleInfo)
          if (result.meta.status !== 201) return this.$message.error(result.meta.msg)
          this.$message.success(result.meta.msg)
          this.getRoleList()
        })
        this.addRoleDialogVisible = false
      },
      showRoleAuthDialog(roleid) {
        // 显示角色授权对话框
        this.roleAuthDialogVisible = true
        // 先将要授权的角色id记录下来
        this.roleAuth.id = roleid
        // 调用函数获取权限tree数据
        this.getRightsList()
      },
      submitRoleAuthInfo() {
        this.roleAuthDialogVisible = false
      },
      handleRoleAUthClose() {},
      async getRightsList() {
        const result = await this.$http.get('rights/tree', this.queryInfo)
        if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
        this.rightsList = result.data
        console.log(this.rightsList)
        this.$message.success(result.meta.msg)
      }
    }
  }
</script>

<style>
  .rowBottomBorder {
    border-bottom: 1px solid #ccc;
  }

  .rowTopBorder {
    border-top: 1px solid #ccc;
  }
</style>
